/**
 *
 * @description: 对控制器的封装
 * @author: junyong.hong
 * @createTime: 2018/12/4
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const mongoose = require('mongoose')
const User = mongoose.model('User')
const { getOAuth, getWechat } = require('../../wechat/index')
const util = require('../../wechat-lib/util')

/**
 * 通用方法封装：获取access_token、Ticket
 * @param url
 * @returns {Promise.<*|{noncestr, timestamp, signature}>}
 */
exports.getSignature = async (url) => {
    // const url = ctx.href
    const client = getWechat()

    // 获取access_token异步方法
    // 调用wechat/index.js，wechat/index.js又去调用wechat-lib/index.js里的方法（实际是调用这里的方法）
    const data = await client.fetchAccessToken()

    const token = data.access_token

    // 获取Ticket
    const ticketData = await client.fetchTicket(token)
    const ticket = ticketData.ticket

    let params = client.sign(ticket, url)
    params.appId = client.appID

    return params
}

/**
 * 通用方法封装：网页授权
 * @param scope
 * @param target
 * @param state
 * @returns {Promise.<*>}
 */
exports.getAuthorizeURL = async (scope, target, state) => {
    const oauth = getOAuth()
    // 调用wechat/index.js，wechat/index.js又去调用wechat-lib/oauth.js里的方法（实际是调用这里的方法）
    const url = await oauth.getAuthorizeURL(scope, target, state)

    return url
}

exports.getUserinfoByCode = async (code) => {
    const oauth = getOAuth()
    const data = await oauth.fetchAccessToken(code)
    const userData = await oauth.getUserInfo(data.access_token, data.openid)

    return userData
}


exports.saveWechatUser = async (userData) => {
    let query = {
        openid: userData.openid
    }

    if (userData.unionid) {
        query = {
            unionid: userData.unionid
        }
    }

    let user = await User.findOne(query)
    if (!user) {
        user = new User({
            openid: [userData.openid],
            unionid: userData.unionid,
            nickname: userData.nickname,
            email: (userData.unionid || userData.openid) + '@wx.com',// 虚拟邮箱
            province: userData.province,
            country: userData.country,
            city: userData.city,
            gender: userData.gender || userData.sex
        })

        user = await user.save()
    }

    return user
}

// 持久化用户
// 对用户打标签和统计
exports.saveMPUser = async (message, from = '') => {
    let openid = message.FromUserName
    let count = 0

    // 如果是扫码
    // let sceneId = message.EventKey
    // if (sceneId && sceneId.indexOf('qrscene_') > -1) {
    //     sceneId = sceneId.replace('qrscene_' , '')
    // }

    let user = await User.findOne({
        openid: openid
    })

    let mp = require('../../wechat/index')
    let client = mp.getWechat()
    let userInfo = await client.handle('getUserInfo', openid)

    // 扫码
    // if (sceneId === 'imooc') {
    //     from = 'imooc'
    // }

    if (!user) {
        let userData = {
            from: 'imooc',
            openid: [userInfo.openid],
            unionid: userInfo.unionid,
            nickname: userInfo.nickname,
            email: (userInfo.unionid || userInfo.openid) + '@wx.com',// 虚拟邮箱
            province: userInfo.province,
            country: userInfo.country,
            city: userInfo.city,
            gender: userInfo.gender || userInfo.sex
        }

        user = new User(userData)
        user = await user.save()
    }

    if (from === 'imooc') {
        let tagid

        count = await User.count({
            from: 'imooc'
        })

        try {
            let tagsData = await client.handle('fetchTags')

            tagsData = tagsData || {}
            const tags = tagsData.tags || []
            const tag = tags.filter(tag => {
                return tag.name === 'imooc'
            })

            if (tag && tag.length > 0) {
                tagid = tag[0].id
                count = tag[0].count || 0
            } else {
                let res = await client.handle('createTag', 'imooc')

                tagid = res.tag.id
            }

            if (tagid) {
                await client.handle('batchTag', [openid], tagid)
            }

        } catch (err) {
            console.log(err)
        }
    }

    return {
        user,
        count
    }
}



